package com.jeeplus.modules.web.web;

import com.jeeplus.common.config.Global;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.monitor.utils.Achieve;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.web.entity.*;
import com.jeeplus.modules.web.entity.YjMaintenance;
import com.jeeplus.modules.web.mapper.WxAgentsMapper;
import com.jeeplus.modules.web.mapper.YjEquipmentMapper;
import com.jeeplus.modules.web.service.WxEquipmentAddressService;
import com.jeeplus.modules.web.service.YjEquipmentService;
import com.jeeplus.modules.web.service.YjMaintenanceService;
import com.jeeplus.modules.web.service.YjMaintenanceService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

@Controller
@RequestMapping(value = "${adminPath}/web/yjMaintenance")
public class YjMaintenanceController extends BaseController {
    @Autowired
    private YjMaintenanceService yjMaintenanceService;
    @Autowired
    private WxEquipmentAddressService wxEquipmentAddressService;
    @Autowired
    private WxAgentsMapper wxAgentsMapper;
    @Autowired
    private YjEquipmentService yjEquipmentService;
    @Autowired
    private YjEquipmentMapper yjEquipmentMapper;


    @ModelAttribute
    public YjMaintenance get(@RequestParam(required = false) String id) {
        YjMaintenance entity = null;
        if (StringUtils.isNotBlank(id)) {
            entity = yjMaintenanceService.get(id);
        }
        if (entity == null) {
            entity = new YjMaintenance();
        }
        return entity;
    }

    /**
     * 设备维护信息列表页面
     */
    @RequiresPermissions("web:yjMaintenance:list")
    @RequestMapping(value = { "list", "" })
    public String list(Integer pageIndex, Model model) {
        if(pageIndex==null){
            pageIndex = 1;
        }
        WxAgents wxAgents = new WxAgents();
        wxAgents.setStatus(1);
        User currentUser = UserUtils.getUser();
        WxAgents currentAgents = null;
        List<WxAgents> list = null;

        if (!currentUser.getId().equals("1")) {// 不是管理员，权限过滤
            currentAgents = wxAgentsMapper.findUniqueByProperty("username", currentUser.getMobile());
            Map<String, List<WxAgents>> listmap = recursionAgents(Integer.parseInt(currentAgents.getId()));
            model.addAttribute("childList", listmap.get("childList"));
            model.addAttribute("shopList", listmap.get("shopList"));
        } else {
            wxAgents.setAgentLevel(0);
            list = wxAgentsMapper.selectList(wxAgents);
            model.addAttribute("list", list);
        }
        model.addAttribute("pageIndex",pageIndex);
        return "modules/web/yjMaintenanceList";
    }

    /**
     * 设备维护信息列表数据 包括1.直接绑定于自己的设备维护，2.其下属代理或门店绑定的设备维护
     */
    @ResponseBody
    @RequiresPermissions("web:yjMaintenance:list")
    @RequestMapping(value = "data")
    public Map<String, Object> data(YjMaintenance yjMaintenance, HttpServletRequest request, HttpServletResponse response,
                                    Model model) {

        User currentUser = UserUtils.getUser();
        WxAgents wxAgents = new WxAgents();

        if (!currentUser.getId().equals("1")) {
            // wxAgents.setUserName(currentUser.getMobile());
            wxAgents = wxAgentsMapper.findUniqueByProperty("username", currentUser.getMobile());
            yjMaintenance.setAgents(wxAgents);
        }
        Page<YjMaintenance> page = yjMaintenanceService.findPage(new Page<YjMaintenance>(request, response), yjMaintenance);
        return getBootstrapData(page);
    }


    /**
     * 查看，增加，编辑设备信息表单页面
     */
    @RequiresPermissions(value = { "web:yjMaintenance:view", "web:yjMaintenance:add",
            "web:yjMaintenance:edit" }, logical = Logical.OR)
    @RequestMapping(value = "form")
    public String form(String id, Model model, Integer pageIndex) {
        YjEquipment yjEquipment = yjEquipmentService.get(id);
        YjMaintenance yjMaintenance = new YjMaintenance();
        yjMaintenance.setEquipment(yjEquipment);
        yjMaintenance.setAgents(yjEquipmentMapper.getAgents(yjEquipment.getNumber()));
        yjMaintenance.setMaintenance(500);
        BigDecimal duration = new BigDecimal(yjEquipment.getDuration()).divide(new BigDecimal(60),0,BigDecimal.ROUND_HALF_UP);
        yjMaintenance.setDuration(duration.intValue());
        model.addAttribute("yjMaintenance", yjMaintenance);
        model.addAttribute("pageIndex", pageIndex);
        if (StringUtils.isBlank(yjMaintenance.getId())) {// 如果ID是空为添加
            model.addAttribute("isAdd", true);
        }
        return "modules/web/yjMaintenanceForm";
    }

    /**
     * 保存设备信息
     */
    @RequiresPermissions(value = { "web:yjMaintenance:add", "web:yjMaintenance:edit" }, logical = Logical.OR)
    @RequestMapping(value = "save")
    public String save(YjMaintenance yjMaintenance, RedirectAttributes redirectAttributes, Integer pageIndex) throws Exception {
        // 新增或编辑表单保存
        yjMaintenanceService.save(yjMaintenance);// 保存
        //修改设备的下次检查时间
        yjEquipmentService.updateMaintenance(yjMaintenance.getEquipment().getNumber(),yjMaintenance.getMaintenance());
        addMessage(redirectAttributes, "保存设备信息成功");
        return "redirect:" + Global.getAdminPath() + "/web/yjEquipment/?repage&maintenance=1&pageIndex="+pageIndex;
    }

    private Map<String, List<WxAgents>> recursionAgents(Integer parentId) {
        WxAgents wxAgents = new WxAgents();
        wxAgents.setParentId(parentId);
        wxAgents.setStatus(1);

        List<WxAgents> childList = wxAgentsMapper.selectList(wxAgents);
        List<WxAgents> shopList = new ArrayList<WxAgents>();

        for (Iterator<WxAgents> iterator = childList.iterator(); iterator.hasNext();) {
            WxAgents elem =  iterator.next();
            if (elem.getAgentLevel() == 3) {
                shopList.add(elem);
                iterator.remove();
            } else if (elem.getId().equals(String.valueOf(parentId))) {
                iterator.remove();
            }
        }
        HashMap<String, List<WxAgents>> hashMap = new HashMap<>();
        hashMap.put("childList", childList);
        hashMap.put("shopList", shopList);
        return hashMap;

    }
}
